// pages/attendance.ts
import { calcPointDist, formatTime } from "../../../utils/util"
import AttendanceApi from "../../../api/AttendanceApi"
import Toast from "tdesign-miniprogram/toast/index"
import DictApi from "../../../api/DictApi"

Page({
  /**
   * 页面的初始数据
   */
  data: {
    lat: "",
    lng: "",
    circles: [{
      latitude: 31.29834,
      longitude: 120.58419,
      radius: 200,
      fillColor: "rgba(111,96,248,0.5)",
      color: "rgba(136,0,215,0.78)"
    }],
    time: formatTime(new Date()),
    signTime: undefined,
    exitTime: undefined,
  },
  interval: null,
  mapCtx: null,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // @ts-ignore
    this.interval = setInterval(() => {
      this.setData({ time: formatTime(new Date()) })
    }, 1000)
    this.queryPoint()
  },
  queryPoint() {
    DictApi.getById(1).then((res: any) => {
      let data: Dict = res.data[0]
      let [longitude, latitude]: any = data.value?.split(';')
      this.setData({ circles: [{ ...this.data.circles[0], longitude, latitude }] })
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // @ts-ignore
    this.mapCtx = wx.createMapContext('myMap')
    setTimeout(() => {
      // @ts-ignore
      this.mapCtx.moveToLocation()
    }, 100)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const _this: any = this
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const { latitude, longitude } = res
        _this.setData({ lat: latitude, lng: longitude })
      },
      fail(res) {
        console.log(res)
      }
    })
    this.queryData()
  },

  queryData() {
    AttendanceApi.getSignTime().then((res: any) => {
      this.setData({ ...res.data[0] })
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },

  handleTimeTap() {
    // @ts-ignore
    const { id, lat, lng, circles } = this.data
    let dist = calcPointDist(Number(lat), Number(lng), circles[0].latitude, circles[0].longitude)
    if (dist > 0.002) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: "超出打卡范围",
      })
      return
    }
    const _this = this
    AttendanceApi.signIn({ id, lat, lng }).then(_ => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '打卡成功',
        theme: 'success',
        direction: 'column',
      })
      _this.queryData()
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.interval && clearInterval(this.interval)
    this.interval = null
  },

})
